export interface SmoothOptions {
    duration?: number,
}

export interface Smooth {
    push: Function,
    stop: (callback?: () => void) => void,
    clear: Function,
    start: Function
}

export function Smooth(callback: Function, options: SmoothOptions = {
    duration: 8
}): Smooth {
    const cache: Array<string> = [];
    let timer: number = -1;
    return {
        push: function(str: string) {
            cache.push(...str.split(''));            
        },
        stop: function(callback?: () => void){
            const delay_timer = setInterval(() => {
                if (cache.length == 0) {
                    clearInterval(timer);
                    clearInterval(delay_timer);
                    callback && callback();
                }
            }, 100)
        },
        clear: function() {
            cache.length = 0;
        },
        start: function() {
            timer = setInterval(() => {
                if (cache[0]) {                    
                    callback(cache[0]);
                    cache.shift();
                }
            }, options.duration);
        }
    }
}
